<?php
/**
 * Created by PhpStorm.
 * User: zgh
 * Date: 2021-07-21
 * Time: 11:41
 */

namespace app\admin\service;

use app\admin\item\ItemLoader;
use app\admin\pipeline\ItemAdapter;
use app\admin\validate\RoleValidate;
use app\common\model\RoleModel;
use app\common\model\RolePrivilegeModel;
use app\common\model\SystemNodeModel;
use think\Db;
use think\facade\Hook;


class RoleService
{
    public static function getByID($id)
    {
        $adapter = new ItemAdapter(RoleModel::class);
        return $adapter->get($id)->getModel();
    }

    public static function getList($params)
    {
        $pagination = filter_pagination(@$params['page'], @$params['limit']);
        $data = [];
        $query = RoleModel::where([['status', '<>', -1]])->order(["id" => "asc"]);
        $data['total'] = $query->count();
        $data['dataList'] = [];
        if ($data['total']) {
            $data['dataList'] = $query->limit($pagination['start'], $pagination['limit'])->select()->toArray();
        }
        return $data;
    }


    public static function save($params)
    {
        $loader = new ItemLoader();
        $item = $loader->addVal($params)->addVerify(RoleValidate::class)->loadItem();
        $adapter = new ItemAdapter(RoleModel::class);
        $res = $adapter->save($item);
        if ($res) {
            return $adapter->getId();
        } else {
            return false;
        }
    }

    public static function del($params)
    {
        $adapter = new ItemAdapter(RoleModel::class);
        return $adapter->whereUpdate([["id", "in", $params['id']]], ["status" => -1]);
    }


    public static function authorizeSave($params)
    {
        Db::startTrans();
        //注册一个删除后操作的钩子
        Hook::add("del_role", function ($params) {
            $role_id = $params['role_id'];
            $node_arr = $params['nodes'];
            $insert_arr = [];
            foreach ($node_arr as $node) {
                array_push($insert_arr, [
                    "role_id" => $role_id,
                    "node" => $node
                ]);
            }
            if ($insert_arr) {
                $adapter = new ItemAdapter(RolePrivilegeModel::class);
                $adapter->saveAll($insert_arr);
            }
        });
        $role_id = $params['id'];
        $node_arr = !empty($params['nodes']) ? $params['nodes'] : [];
        $adapter = new ItemAdapter(RolePrivilegeModel::class);
        $adapter->hookAdd("del_role", ['role_id' => $role_id, "nodes" => $node_arr])->whereDel(["role_id" => $role_id]);
        Db::commit();
        return true;
    }


    /**
     * 根据角色id 获取授权节点
     * @param $authId
     * @return array
     */
    public static function getAuthorizeNodeListById($authId)
    {
        $checkNodeList = RolePrivilegeModel::where(["role_id" => $authId, "status" => 1])->column("node"); //已经存在的节点
        $checkNodeList = array_unique($checkNodeList);
        $nodelList = SystemNodeModel::field('id,node,title,type,is_auth')->select()->toArray();
        $newNodeList = [];
        foreach ($nodelList as $vo) {
            if ($vo['type'] == 1) {
                $vo = array_merge($vo, ['field' => 'node', 'spread' => true]);
                $vo['checked'] = false;
                $vo['title'] = "{$vo['title']}【{$vo['node']}】";
                $children = [];
                foreach ($nodelList as $v) {
                    if ($v['type'] == 2 && strpos($v['node'], $vo['node'] . '/') !== false) {
                        $v = array_merge($v, ['field' => 'node', 'spread' => true]);
                        $v['checked'] = in_array($v['node'], $checkNodeList) ? true : false;
                        $v['title'] = "{$v['title']}【{$v['node']}】";
                        $children[] = $v;
                    }
                }
                !empty($children) && $vo['children'] = $children;
                $newNodeList[] = $vo;
            }
        }
        return $newNodeList;
    }
}